package com.cdvtc.fengchao.Servlet;

import com.cdvtc.fengchao.dao.GeneralDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/userManagementServlet")
public class UserManagementServlet extends HttpServlet {

    private GeneralDao generalDao = new GeneralDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询用户数据
        List<Map<String, Object>> users = generalDao.getUsers();
        System.out.println("查询到的用户数量: " + users.size());
        request.setAttribute("users", users);

        // 转发到JSP页面
        request.getRequestDispatcher("/admin/users.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("add".equals(action)) {
            // 添加用户
            String username = request.getParameter("username");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            int result = generalDao.addUser(username, phone, address, email, password);
            if (result > 0) {
                System.out.println("用户添加成功");
            } else {
                System.out.println("用户添加失败");
            }
        } else if ("update".equals(action)) {
            // 更新用户
            int id = Integer.parseInt(request.getParameter("id"));
            String username = request.getParameter("username");
            String phone = request.getParameter("phone");
            String address = request.getParameter("address");
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            int result = generalDao.updateUser(id, username, phone, address, email, password);
            if (result > 0) {
                System.out.println("用户更新成功");
            } else {
                System.out.println("用户更新失败");
            }
        } else if ("delete".equals(action)) {
            // 删除用户
            int id = Integer.parseInt(request.getParameter("id"));
            int result = generalDao.deleteUser(id);
            if (result > 0) {
                System.out.println("用户删除成功");
            } else {
                System.out.println("用户删除失败");
            }
        }
        response.sendRedirect(request.getContextPath() + "/admin/userManagementServlet");
    }
}